const Router = require('koa-router');
const { findByDate, create, update } = require('../controllers/historyController');
const { getCache, getSectorList, getConceptList, getConceptHistoryCache, updateLowPriceCacheByCode, updateHighPriceCacheByCode } = require('../controllers/cachedController');

const router = new Router();

router.get('/api/stocks', (ctx) => {
    let predictionStocks = getCache()
    // 按涨跌幅排序
    const sortedStocks = [...predictionStocks].sort((a, b) => Math.abs(b.changePercent) - Math.abs(a.changePercent))
    const topGainers = sortedStocks.filter(s => s.changePercent >= 0)
    const topLosers = sortedStocks.filter(s => s.changePercent < 0)
    const recommendations = predictionStocks
        .filter(p => p.predictionScore >= 65)
        .sort((a, b) => b.predictionScore - a.predictionScore)
    ctx.body = {
        topGainers,
        topLosers,
        recommendations
    }
});

router.post('/api/stocks/codes', async (ctx) => {
    const { codes } = ctx.request.body;
    let stocks = getCache();
    ctx.body = codes.map(code => {
        return stocks.find(item => item.code === code)
    })
});

router.post('/api/stocks/updatePrice', async (ctx) => {
    const { code, lowPrice, highPrice } = ctx.request.body;
    
    updateLowPriceCacheByCode(code, lowPrice)
    updateHighPriceCacheByCode(code, highPrice)
    return ctx.body = { success: true }
});

router.post('/api/history/save', (ctx) => {
    const { data } = ctx.request.body;
    if (data.length === 0) {
        ctx.body = { success: true }
        return
    }
    data.forEach(item => {
        if (item._id) {
            update(item._id, item)
        } else {
            create(item)
        }
    })

    ctx.body = { success: true }
});

// 按日期查找
router.get('/api/historyByDate/:date', async (ctx) => {
    ctx.body = await findByDate(ctx.params.date)
});

// 获取板块信息
router.get('/api/sectorList', async (ctx) => {
    ctx.body = getSectorList()
});

// 获取概念信息
router.get('/api/conceptList', async (ctx) => {
    ctx.body = getConceptList()
});

// 获取新概念
router.get('/api/newConceptList', async (ctx) => {
    let newList = []
    try {
        let conceptHistory = getConceptHistoryCache()
        let conceptList = getConceptList()
        newList = conceptList.filter(item => !conceptHistory.includes(item))
    } catch (error) {
        console.log('获取新概念失败')
    }

    ctx.body = newList
});
module.exports = router;